package com.blueflamedev.effects.plugins
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.filters.BlurFilter;
	import flash.geom.Matrix;
	import flash.geom.Point;

	/**
	 * The <code>Trails</code> Plugin creates trails behind the particles. The trails blur out until they fade away behind the particle.
	 * Properties can be set to control the length of the trails.
	 * 
	 * @author Eric Smith
	 */	
	public class Trails extends Plugin implements IPlugin
	{
		public var blurAmount:Number;
		
		private var _canvasData:BitmapData;
		private var _canvas:Bitmap;
		
		/**
		 * Creates an instance of a Trails plugin.
		 *  
		 * @param blurAmount The amount of blur to apply to the trail every frame.
		 */		
		public function Trails(blurAmount:Number = 4)
		{
			super();
			this.blurAmount = blurAmount;
		}
		
		override public function start():void
		{
			super.start();
			
			if (seed.stage)
			{
				setup();
			} else
			{
				seed.addEventListener(Event.ADDED_TO_STAGE, onSeedAddedToStage);
			}
		}
		
		override public function stop():void
		{
			super.stop();
		}
		
		private function onSeedAddedToStage(event:Event):void
		{
			setup();
		}
		
		private function setup():void
		{
			_canvasData = new BitmapData(seedRef.stage.stageWidth, seedRef.stage.stageHeight, true, 0x000000);
			_canvas = new Bitmap(_canvasData);
			_canvas.smoothing = true;
			seedRef.stage.addChild(_canvas);
			
			seedRef.addEventListener(Event.ENTER_FRAME, drawToCanvas);
		}
		
		private function drawToCanvas(event:Event):void
		{
			var matrix:Matrix = new Matrix();
		 	matrix.translate(seedRef.container.x, seedRef.container.y);
		 	_canvasData.draw(seedRef.container, matrix);
		 	var blurFilter:BlurFilter = new BlurFilter(blurAmount, blurAmount);
		 	_canvasData.applyFilter(_canvasData, _canvas.getRect(_canvas), new Point(0, 0), blurFilter);
		}
	}
}